<?php

namespace app\api\controller\ai;

use thinkct\controller\Frontend;
use app\common\model\ai\Group;
use app\common\model\ai\Message as MessageModel;
use thinkct\facade\ChatAI;
use app\admin\model\ai\Config as AiConfig;
use app\common\model\ai\app\Models as AppModel;
use thinkct\facade\ChatData;

class Message extends Frontend
{
    protected array $noNeedLogin = ['index', 'send_text'];

    public function initialize(): void
    {
        parent::initialize();
    }

    /**
     * 获取聊天内容
     */
    public function index(): void
    {
        $group_id = $this->request->get('group_id');
        if(!$group_id) $this->error('分组不能为空');

        $message_list = ChatData::message_list([
            'user_id' => $this->auth->id,
            'group_id' => $group_id,
        ]);

        // 获取分组信息
        $ai_name = AiConfig::where('name', 'ai_name')->value('value');
        $ai_avatar = AiConfig::where('name', 'ai_avatar')->value('value');
        $ai_greeting = AiConfig::where('name', 'ai_greeting')->value('value');
        $group = Group::where(['id'=>$group_id])->find();
        if($group) {
            $ai_name = $group->name;
            $ai_avatar = $group->cover;
            // 获取关联app
            $app = AppModel::where('id', $group->app_id)->find();
            if($app) {
                $ai_greeting = $app->greeting;
            }
        }

        $this->success('获取成功', [
            'data' => $message_list,
            'ai_name' => $ai_name,
            'ai_avatar' => $ai_avatar,
            'ai_greeting' => $ai_greeting,
            'model' => $group->model ?? 'gpt-3.5-turbo',
        ]);
    }

    /**
     * 发送聊天内容
     */
    public function send_text(): void
    {
        // 设置最大超时时间10分钟
        set_time_limit(2000);
        $group_id = $this->request->param('group_id');
        $content = $this->request->param('content');
        if ($content == '') $this->error('内容不能为空');

        // 获取分组信息
        $group = Group::where(['id'=>$group_id])->find();
        if(!$group) {
            $group = ChatData::createGroup($content, $this->auth->id);
            if(!$group) $this->error(ChatData::getError());
            $group_id = $group->id;
        } else {
            // 模型为空更新模型
            if(!$group->model) {
                // 获取可用的模型key
                $model_key = ChatAI::getModelKey();
                if($model_key) {
                    $group->model_id = $model_key->model_id;
                    $group->model = $model_key->model;
                }
            }
            $group->title = $content;
            $group->save();
        }

        ### gpt-4-vision-preview
        $file_list = $this->request->param('file_list');
        if($file_list) {
            $group->model_id = 11;
            $group->model = 'gpt-4-vision-preview';
        }
        ### gpt-4-vision-preview


        // 发送聊天内容
        $sendText = ChatData::send_text($content, $group);

        // 错误提示
        if (!$sendText['status']) {
            $this->error($sendText['content']);
        }

        // 创建消息
        $Message = MessageModel::create([
            'user_id' => $this->auth->id,
            'group_id' => $group_id,
            'title' => $content,
            'content' => $sendText['content'],
            'model' => $group->model,
            'total_token' => mb_strlen($sendText['content'], 'utf-8') + mb_strlen($content, 'utf-8'),
        ]);

        ### gpt-4-vision-preview 上传文件
        if($file_list) {
            // 循环写入文件
            foreach ($file_list as $file) {
                \app\common\model\ai\MessageFile::create([
                    'message_id' => $Message->id,
                    'name' => $file['name'],
                    'url' => $file['url'],
                ]);
            }
        }
        ### gpt-4-vision-preview

        // 预设回复
        if ($sendText['type'] == 'success') {
            //ChatData::event_stream($sendText['content']);
            $this->success($sendText['content']);
        }
        //$this->success($sendText);
    }

    /**
     * 删除聊天内容
     */
    public function delete(): void
    {
        $group_id = $this->request->post('group_id', '');
        $id = $this->request->post('id', '');

        // 删除列表
        $message = MessageModel::where(['group_id'=>$group_id, 'user_id'=> $this->auth->id]);
        if($id) {
            $message = $message->where('id', $id);
        }
        $message = $message->delete();
        if ($message) {
            $this->success($id ? '删除成功' : '清除成功');
        } else {
            $this->error($id ? '删除失败' : '清除失败');
        }
    }
}